﻿/****************************************
 * Few good KTV download website:
 * http://www.chinaktv.net
 * http://www.mtv-ktv.net
 * http://www.mtv-mtv.com
 * http://www.kk07.com
 * http://www.zqmtv.com
 ****************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HtmlAgilityPack;
using System.Data.Common;
using System.Data;
using System.Configuration;
using System.Data.OleDb;
using System.IO;
using System.Collections;
using System.Threading;
using System.Windows.Threading;
using System.ComponentModel;
using System.Net;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace CrazyKTVfromCashBox
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private System.ComponentModel.BackgroundWorker backgroundWorker = new System.ComponentModel.BackgroundWorker();

        public MainWindow()
        {
            InitializeComponent();
            datePicker1.Text = DateTime.Now.AddMonths(-1).ToShortDateString();
            datePicker2.Text = DateTime.Now.ToShortDateString();

            this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_DoWork);
            this.backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted);
            this.backgroundWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker_ProgressChanged);

            this.backgroundWorker.WorkerSupportsCancellation = true;
            this.backgroundWorker.WorkerReportsProgress = true;

        }


        private CrazyKTVfromCashBox.CrazySongDataSet crazySongDataSet;
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            button1.IsEnabled = false;
            button3.Visibility = Visibility.Visible;
            // ext_CashBoxDataGrid.IsEnabled = false;
            ext_CashBoxDataGrid.Visibility = Visibility.Hidden;

            crazySongDataSet = ((CrazyKTVfromCashBox.CrazySongDataSet)(this.FindResource("crazySongDataSet")));
            clearTable_ext_CashBox();
            crazySongDataSetstatic = crazySongDataSet;
            textBlock1.Text = "downloading page 1...";

            finalpageNumber = int.Parse(textBox1.Text.Trim().ToString());

            // Calls DoWork on secondary thread 
            this.backgroundWorker.RunWorkerAsync();


        }

        private static int finalpageNumber = 0;

        /// <summary> 
        /// Runs on secondary thread. 
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        /// <remarks></remarks> 
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // call long running process and get result 

            e.Result = this.processGetCashboxAllSongList(finalpageNumber);

            // Cancel if cancel button was clicked. 
            if (this.backgroundWorker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }
        }


        private void backgroundWorker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            // Update UI with % completed. 
            this.textBlock1.Text = e.ProgressPercentage.ToString() + " pages processed out of " + finalpageNumber.ToString() + ".";

            crazySongDataSet = crazySongDataSetstatic;
        }


        /// <summary> 
        /// Called when DoWork has completed. 
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        /// <remarks></remarks> 
        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // Back on primary thread, can access ui controls 
            // wpfProgressBarAndText.Visibility = Visibility.Collapsed;

            if (e.Cancelled)
            {
                this.textBlock1.Text = "Process Cancelled.";
            }
            else
            {
                this.textBlock1.Text = "Processing completed. " + (string)e.Result + " pages processed.";
                crazySongDataSet = crazySongDataSetstatic;
            }


            this.button1.IsEnabled = true;
            button3.Visibility = Visibility.Hidden;

            //   ext_CashBoxDataGrid.IsEnabled = true;  //too fast may cause error

        }

        /// <summary> 
        /// Handles click event for cancel button. 
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        /// <remarks></remarks> 
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            // Cancel the asynchronous operation. 
            this.backgroundWorker.CancelAsync();

            // Enable the Start button. 
            this.button1.IsEnabled = true;


            button3.Visibility = Visibility.Hidden;

        }


        private static CrazyKTVfromCashBox.CrazySongDataSet crazySongDataSetstatic;
        private static CrazySongDataSetTableAdapters.ext_CashBoxTableAdapter ext_CashBoxTableAdapterstatic = new CrazySongDataSetTableAdapters.ext_CashBoxTableAdapter();

        private string processGetCashboxAllSongList(int finalPageNumber)
        {

            int j = 0;


            for (int i = 1; i <= finalPageNumber; i++)
            {
                // don't continue if cancel button clicked 
                if (this.backgroundWorker.CancellationPending)
                {
                    return "";
                }

                j = i;

                if ((j == i) & (backgroundWorker != null) && backgroundWorker.WorkerReportsProgress)
                {
                    //crazySongDataSet.ext_CashBox.Merge(getCashboxAllSongList(i.ToString()));
                    //(new CrazySongDataSetTableAdapters.ext_CashBoxTableAdapter()).Update(crazySongDataSet);

                    crazySongDataSetstatic.ext_CashBox.Merge(getCashboxAllSongList(i.ToString()));
                    ext_CashBoxTableAdapterstatic.Update(crazySongDataSetstatic);
                    backgroundWorker.ReportProgress(i);
                }


            }

            return j.ToString();
        }


        private DataTable getCashboxAllSongList(string pageNumber)
        {
            DataTable dt = (new CrazySongDataSet()).Tables["ext_CashBox"].Clone();

            HtmlWeb hw = new HtmlWeb();
            HtmlDocument doc = hw.Load("http://www.cashboxparty.com/mysong/mysong_search_r.asp?Page=" + pageNumber);
            // string strResult = "";

            var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
                        from row in table.SelectNodes("tr").Cast<HtmlNode>()
                        select new { Table = table.Id, RowText = row.InnerText, RowHtml = row.InnerHtml };

            foreach (var row in query)
            {
                HtmlDocument doc2 = new HtmlDocument();
                doc2.LoadHtml(row.RowHtml);

                var query2 = from cell in doc2.DocumentNode.SelectNodes("th|td").Cast<HtmlNode>()
                             select new { Celltext = cell.InnerText };

                int intColumnNumber = 0;
                DataRow dr = dt.NewRow();

                foreach (var cell in query2)
                {
                    if (intColumnNumber < 4)
                    {
                        dr[intColumnNumber] = cell.Celltext.Trim().Replace("、", "&");
                        intColumnNumber = intColumnNumber + 1;
                    }
                }

                try
                {
                    int tempX;
                    if (int.TryParse(dr[0].ToString(), out tempX))
                    {
                        dr[4] = DateTime.Now;
                        dt.Rows.Add(dr);
                    }

                }
                catch { }
            }

            //using (StreamWriter outfile = new StreamWriter(@"~Cashboxsongbook.txt"))
            //{
            //    outfile.Write(strResult.ToString());
            //}

            return dt;

        }


        private bool checkTable(string tablename)
        {
            DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
            DataTable userTables = null;

            using (DbConnection connection = factory.CreateConnection())
            {
                connection.ConnectionString = ConfigurationManager.ConnectionStrings["CrazyKTVfromCashBox.Properties.Settings.CrazySongConnectionString"].ConnectionString;

                // We only want user tables, not system tables
                string[] restrictions = new string[4];
                restrictions[3] = "Table";

                connection.Open();

                // Get list of user tables
                userTables = connection.GetSchema("Tables", restrictions);
            }

            foreach (DataRow dr in userTables.Rows)
            {
                if (dr[2].ToString().ToLower().Trim() == tablename.ToLower().Trim())
                {
                    return true;
                }
            }
            return false;

        }

        private bool createTable_ext_CashBox()
        {
            string strcommand = "CREATE Table ext_CashBox (cashbox_id TEXT(6),song_lang TEXT(20),song_name TEXT(250),singer_name TEXT(250), createDate DATETIME)";

            OleDbConnection conDatabase = new OleDbConnection(ConfigurationManager.ConnectionStrings["CrazyKTVfromCashBox.Properties.Settings.CrazySongConnectionString"].ConnectionString);
            OleDbCommand aCommand = new OleDbCommand(strcommand, conDatabase);

            conDatabase.Open();
            aCommand.ExecuteNonQuery();
            conDatabase.Close();

            return true;
        }

        private bool clearTable_ext_CashBox()
        {
            string strcommand = "delete from ext_CashBox";

            OleDbConnection conDatabase = new OleDbConnection(ConfigurationManager.ConnectionStrings["CrazyKTVfromCashBox.Properties.Settings.CrazySongConnectionString"].ConnectionString);
            OleDbCommand aCommand = new OleDbCommand(strcommand, conDatabase);

            conDatabase.Open();
            aCommand.ExecuteNonQuery();
            conDatabase.Close();

            return true;
        }


        private void button2_Click(object sender, RoutedEventArgs e)
        {
            string path = @"~CashBox.html";

            try { File.Delete(path); }
            catch { }




            DateTime startDt = DateTime.Parse(datePicker1.Text.ToString());
            DateTime endDt = DateTime.Parse(datePicker2.Text.ToString());
            TimeSpan ts = startDt - endDt;

            if (ts.Days <= 0)
            {
                DateTime tempDt = endDt;
                endDt = startDt;
                startDt = tempDt;
                ts = startDt - endDt;
            }



            DateTime dt = startDt;

            for (int i = 0; i <= ts.Days; i++)
            {
                DateTime loopDate = dt.AddDays(-i);

                HtmlWeb hw = new HtmlWeb();
                HtmlDocument doc = hw.Load(string.Format(@"http://www.cashboxparty.com/billboard/billboard_newsong.asp?sdate={0}", loopDate.ToString("yyyy/MM/dd")));
                // MessageBox.Show(string.Format(@"http://www.cashboxparty.com/billboard/billboard_newsong.asp?sdate={0}", loopDate.ToString("yyyy/MM/dd")));
                string strResult = doc.DocumentNode.InnerHtml.ToString();
                // doc.Save("~.txt");

                // This text is added only once to the file.

                if (strResult.IndexOf(@"<tr height=""26"">") > 0)  //which means there is no data.
                {
                    if (!File.Exists(path))
                    {
                        // Create a file to write to.
                        using (StreamWriter sw = File.CreateText(path))
                        {
                            sw.Write(strResult.ToString());
                        }
                    }
                    else
                    {
                        // This text is always added, making the file longer over time
                        // if it is not deleted.
                        using (StreamWriter sw = File.AppendText(path))
                        {
                            sw.Write(strResult.ToString());
                        }
                    }
                }


            }

            ////open html
            //Create a new process.
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.EnableRaisingEvents = false;
            //Here you can also specify a html page on local machine
            proc.StartInfo.FileName = path;

            try
            {
                proc.Start();
            }
            catch (Exception e5)
            {
                MessageBox.Show("There is no song list in this period.");
            }




        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!checkTable("ext_CashBox")) createTable_ext_CashBox();

                CrazyKTVfromCashBox.CrazySongDataSet crazySongDataSet = ((CrazyKTVfromCashBox.CrazySongDataSet)(this.FindResource("crazySongDataSet")));

                // Load data into the table ext_CashBox. You can modify this code as needed.
                CrazyKTVfromCashBox.CrazySongDataSetTableAdapters.ext_CashBoxTableAdapter crazySongDataSetext_CashBoxTableAdapter = new CrazyKTVfromCashBox.CrazySongDataSetTableAdapters.ext_CashBoxTableAdapter();
                crazySongDataSetext_CashBoxTableAdapter.Fill(crazySongDataSet.ext_CashBox);
                System.Windows.Data.CollectionViewSource ext_CashBoxViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("ext_CashBoxViewSource")));
                ext_CashBoxViewSource.View.MoveCurrentToFirst();
            }
            catch (Exception e1)
            {
                Console.Write("Cannot find the database file so cannot download the song lists to the database..");
                button1.IsEnabled = false;
            }



            // CrazyKTVfromCashBox.DataSet1 dataSet1 = ((CrazyKTVfromCashBox.DataSet1)(this.FindResource("dataSet1")));
        }


        //private CrazyKTVfromCashBox.DataSet1 ds1;
        private CrazyKTVfromCashBox.DataSet1 getDataset1()
        {
            return ((CrazyKTVfromCashBox.DataSet1)(this.FindResource("dataSet1")));
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            //getDataset1();
            //DataSet1.dtSearchKp2pDataTable  dr = new DataSet1.dtSearchKp2pDataTable.;


            /// show all the result headers                 
            try
            {
                singerColumn.Visibility = Visibility.Visible;
                songColumn.Visibility = Visibility.Visible;
                kp2pColumn.Visibility = Visibility.Visible;

                dtSearchKp2pDataGrid.Visibility = Visibility.Hidden;

            }
            catch { }

           


            int j = getDataset1().Tables[0].Rows.Count;  //list the user entered

            for (int i = 0; i < j; i++)
            {
                textBox2.Text = getDataset1().Tables[0].Rows[i][0].ToString().Trim();

                if (textBox2.Text.Length > 0) //only get the data when the search string is not empty
                {
                    //currentPageNumberfromKp2pweb = 0; // it has total of 100 songs in a page.
                    //totalPageNumberfromKp2pweb = 1; // it has total of 100 songs in a page.


                    //singer or songname
                    //http://www.chinaktv.net/SingerV.aspx?sname=Olivia , http://www.chinaktv.net/SingerV.aspx?sname=Olivia(%E7%8E%8B%E4%BF%AA%E5%A9%B7)
                    //http://www.chinaktv.net/search.aspx?update=1&keyword=%E6%9C%88

                    //do
                    //{
                    //    currentPageNumberfromKp2pweb = currentPageNumberfromKp2pweb + 1;
                    //    string _songName = Gmethods.ToSimplified(textBox2.Text.ToString().Trim());
                    //    string kp2p = getKp2p(_songName, comboBox1.SelectedValue.ToString(), currentPageNumberfromKp2pweb.ToString());
                    //} while (totalPageNumberfromKp2pweb > currentPageNumberfromKp2pweb);


                    //currentPageNumberfromKp2pweb = currentPageNumberfromKp2pweb + 1;
                    string _songName = Gmethods.ToSimplified(textBox2.Text.ToString().Trim());
                    //string kp2p = getKp2p(_songName, comboBox1.SelectedValue.ToString(), currentPageNumberfromKp2pweb.ToString());
                    string kp2p = getKp2p(_songName, comboBox1.SelectedValue.ToString(), "1");



                }
            }


            for (int i = 0; i < j; i++)
            {
                try
                {
                    getDataset1().Tables[0].Rows.RemoveAt(0); //because after remove the original i will be push up to position 0
                }
                catch { }
            }


            searchForColumn.Visibility = Visibility.Hidden;

            string strtemp = "";

            if (NoSearchReturnList.Count > 0)
            {
                foreach (object objstr in NoSearchReturnList)
                {
                    strtemp = strtemp + objstr.ToString() + "\r\n";
                }

                MessageBox.Show("Fail to find following:\r\n(Press ctrl+c can copy this to the clipboard)\r\n\r\n" + strtemp);
            }


            MessageBox.Show("此搜尋網站現在只應許每天每個IP回應50個k2p2連接. 如果你看不到連接,只看到'masstime',那就是已經今天的搜尋量,可以換個IP試試看. \r\n\r\n如果您知道有好的 KP2P 的搜尋網站,或者其他軟體,網站的KTV歌曲下載方式,請告知,謝謝!\r\n\r\n");

        }

        private void textBox2_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                button4_Click(sender, e);
            }
        }


        //private int currentPageNumberfromKp2pweb = 0; // it has total of 100 songs in a page.
        //private int totalPageNumberfromKp2pweb = 1; // it has total of 100 songs in a page.

        private string getKp2p(string _songName, string _selectType, string _pageNumber)
        {
            String MyURL;



            //String MyURL2;
            //MyURL2 = Gmethods.UrlEncode2("http://www.mtv-ktv.net/mtv.asp?type=" + _selectType + "&page=" + _pageNumber + "&ktv=" + Gmethods.UrlEncode(_songName, "Unicode"));  //using URLencode2 for song but URLencode for address


            //String MyURL3;
            //MyURL3 = "http://open.dapper.net/RunDapp?dappName=MTVKTVsearch&v=1&applyToUrl=" + MyURL2;  //finalize all string to create full real URL



            _pageNumber = "1";

            if (_selectType == "2") //singer name
            {
                MyURL = string.Format("http://www.chinaktv.net/SingerV.aspx?Page={0}&sname={1}", _pageNumber, Gmethods.UrlEncode(_songName, "Unicode"));   // using UrlEncode method
            }
            else // "1"= SONG NAME OR MIX SINGER AND SONG NAME
            {
                MyURL = string.Format("http://www.chinaktv.net/search.aspx?Page={0}&keyword={1}", _pageNumber, Gmethods.UrlEncode(_songName, "Unicode"));   // using UrlEncode method
            }

            int totalPage = getLastPageForThisSearch(MyURL);



            for (int i = 1; i <= totalPage; i++)
            {
                if (_selectType == "2") //singer name
                {
                    MyURL = string.Format("http://www.chinaktv.net/SingerV.aspx?Page={0}&sname={1}", i, Gmethods.UrlEncode(_songName, "Unicode"));   // using UrlEncode method
                }
                else // "1"= SONG NAME OR MIX SINGER AND SONG NAME
                {
                    MyURL = string.Format("http://www.chinaktv.net/search.aspx?Page={0}&keyword={1}", i, Gmethods.UrlEncode(_songName, "Unicode"));   // using UrlEncode method
                }

                getKp2pAllLinkPerPage(MyURL);
            }
                




            return null;

        }

        private ArrayList NoSearchReturnList = new ArrayList();

        //private string getKp2pEachLink(string realLinkPage)
        //{

        //    String MyURL4 = "http://open.dapper.net/transform.php?dappName=MTVKTVgetsonglinkpage&transformer=CSV&extraArg_fields[]=songlist%40href&applyToUrl=" + Gmethods.UrlEncode2(realLinkPage);
        //    string urlHasKp2p = "";

        //    //string pageSource1 = "";
        //    try
        //    {
        //        HttpWebRequest url = (HttpWebRequest)WebRequest.Create(MyURL4);
        //        HttpWebResponse response = (HttpWebResponse)url.GetResponse();
        //        StreamReader input = new StreamReader(response.GetResponseStream());
        //        string pageSource1 = input.ReadToEnd().ToString();

        //        //Console.WriteLine(pageSource1);
        //        urlHasKp2p = pageSource1;

        //        input.Close();
        //        response.Close();
        //    }
        //    catch (Exception ee)
        //    {
        //        Console.WriteLine(ee.ToString());
        //        return "";
        //    }


        //    string urlKp2p = "";

        //    try
        //    {
        //        Uri uri = new Uri(urlHasKp2p);
        //        //WebRequest url = WebRequest.Create(urlHasKp2p);

        //        WebRequest url = WebRequest.Create(uri);

        //        WebResponse response = url.GetResponse();
        //        StreamReader input = new StreamReader(response.GetResponseStream());
        //        string pageSource = input.ReadToEnd().ToString();

        //        //Console.WriteLine(pageSource);
        //        string regex = @"([']kp2p://.*['])";
        //        Regex r = new Regex(regex, RegexOptions.IgnoreCase);
        //        urlKp2p = r.Matches(pageSource)[0].ToString().Trim('\'');

        //        //textBox3.Text += urlKp2p + "\r\n";



        //        DataRow dr = getDataset1().Tables[0].NewRow();
        //        dr[1] = Gmethods.ToTraditional(Gmethods.getQueryString(urlHasKp2p, "singer"));
        //        dr[2] = Gmethods.ToTraditional(Gmethods.getQueryString(urlHasKp2p, "mtvname"));
        //        dr[3] = urlKp2p.ToString();
        //        getDataset1().Tables[0].Rows.Add(dr);


        //        //url.Close();
        //        input.Close();
        //        response.Close();
        //    }
        //    catch (Exception ee)
        //    {
        //        Console.WriteLine(ee.ToString());
        //        NoSearchReturnList.Add(textBox2.Text.ToString());
        //        return "";
        //    }

        //    return urlKp2p;

        //}


        private int getLastPageForThisSearch(string URL)
        {
            HtmlWeb hw = new HtmlWeb();
            HtmlDocument doc = hw.Load(URL);

            try
            {
                return int.Parse(doc.DocumentNode.SelectNodes("//div[@class='msdn']/a")[doc.DocumentNode.SelectNodes("//div[@class='msdn']/a").Count - 2].InnerHtml);
            }
            catch
            {
                return 1;  //at lease page=1
            }
        }

        private string getKp2pAllLinkPerPage(string MyURL)
        {
            
            ///get song list page

            // Create the web request  

            DataSet ds1 = new DataSet();
            bool findSong = false;


            try
            {
                ////http://open.dapper.net/RunDapp?dappName=MTVKTVsearch&v=1&applyToUrl=http://www.mtv-ktv.net/mtv.asp?type=1&page=1&ktv=%25c4%25be%25cd%25b7%25c8%25cb
                // Get response  
                //request.Timeout = 200000;

                //using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                //{
                //    // Load data into a dataset  
                //    Console.WriteLine(response.GetResponseStream());

                //}



                HtmlWeb hw = new HtmlWeb();
                HtmlDocument doc = hw.Load(MyURL);

                foreach (HtmlNode formNode in doc.DocumentNode.SelectNodes("//tr[@onclick and @onmouseover and @onmouseout]"))
                {
                    HtmlDocument htmlDoc = new HtmlDocument();
                    htmlDoc.LoadHtml(Gmethods.ToTraditional(formNode.InnerHtml));
                    HtmlNodeCollection nodes = htmlDoc.DocumentNode.SelectNodes(".//td");
                    string songID = htmlDoc.DocumentNode.SelectNodes("//a[@target='_self']")[0].Attributes["href"].Value.Split('=')[1];
                    string songTitle = htmlDoc.DocumentNode.SelectNodes("//a[@target='_self']")[0].Attributes["title"].Value;
                    string fileType = nodes[5].InnerHtml.Trim().Split('/')[1].Substring(0, 3);
                    string fileSize = nodes[4].InnerText.Trim();
                    string songSinger = nodes[2].InnerText.Trim();
                    string songLanguage = nodes[3].InnerText.Trim();


                    if (fileType.ToUpper() != "DVD".ToUpper())
                    {
                        WebRequest req = WebRequest.Create("http://www.chinaktv.net/AjaxMethod.aspx");
                        string postData = string.Format("type=FTP.FTPVUI&sender=GetjlAddress&e=%7B%222%22%3A{0}%7D", songID);

                       // req.Proxy = new WebProxy("24.189.74.25:1906");

                        byte[] send = Encoding.Default.GetBytes(postData);
                        req.Method = "POST";
                        req.ContentType = "application/x-www-form-urlencoded";
                        req.ContentLength = send.Length;

                        Stream sout = req.GetRequestStream();
                        sout.Write(send, 0, send.Length);
                        sout.Flush();
                        sout.Close();

                        WebResponse res = req.GetResponse();
                        StreamReader sr = new StreamReader(res.GetResponseStream());
                        string kp2p = sr.ReadToEnd().Trim('\"');

                        DataRow dr = getDataset1().Tables["dtSearchResult"].NewRow();
                        dr[0] = songTitle;
                        dr[1] = songSinger;
                        dr[2] = kp2p;
                        dr[3] = fileType;
                        dr[4] = fileSize;
                        dr[5] = songLanguage;
                        dr[6] = songID;
                        getDataset1().Tables["dtSearchResult"].Rows.Add(dr);

                        findSong = true;
                    }

                }




                //foreach (HtmlNode link in node.SelectNodes("//a[@href]"))
                //{
                //    Console.WriteLine(link.Value);
                //}

                //if (ds1.Tables[4].Rows.Count >= 100)
                //{
                //    totalPageNumberfromKp2pweb = totalPageNumberfromKp2pweb + 1; // this is to handle for the next page if it returns more than one page (100 songs)
                //}

                //for (int i = 0; i < ds1.Tables[4].Rows.Count; i++)
                //{
                //    string realLinkPage = ds1.Tables[4].Rows[i][2].ToString();
                //    getKp2pEachLink(realLinkPage);
                //}
                return null;
            }
            catch (Exception e)
            {
                if (findSong == false)
                {
                    NoSearchReturnList.Add(textBox2.Text.ToString());
                }
                return "";
            }



        }


        void HandleRequestNavigate(object sender, RoutedEventArgs e)
        {
            string navigateUri = hl2.NavigateUri.ToString();

            // if the URI somehow came from an untrusted source, make sure to
            // validate it before calling Process.Start(), e.g. check to see
            // the scheme is HTTP, etc.
            Process.Start(new ProcessStartInfo(navigateUri));
            e.Handled = true;
        }

        void HandleRequestNavigate3(object sender, RoutedEventArgs e)
        {
            string navigateUri = hl3.NavigateUri.ToString();
            Process.Start(new ProcessStartInfo(navigateUri));
            e.Handled = true;
        }

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                searchForColumn.Header = comboBox1.SelectedItem.ToString().Replace(comboBox1.SelectedItem.GetType().FullName, "").Trim(':').Trim();
            }
            catch { }

        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to clear all the information?", "Remove Searched Information", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                getDataset1().Tables[0].Clear();
                searchForColumn.Visibility = Visibility.Visible;
                singerColumn.Visibility = Visibility.Hidden;
                songColumn.Visibility = Visibility.Hidden;
                kp2pColumn.Visibility = Visibility.Hidden;
                NoSearchReturnList.Clear();


                // bring search grid up
                dtSearchKp2pDataGrid.Visibility = Visibility.Visible;

                // clear the result grid
                getDataset1().Tables["dtSearchResult"].Clear();


            }
        }

        private void searchForColumn_PastingCellClipboardContent(object sender, DataGridCellClipboardEventArgs e)
        {
            MessageBox.Show("paste");

            getDataset1().Tables[0].Rows.Add("1111");
            getDataset1().Tables[0].Rows.Add("222");
            getDataset1().Tables[0].Rows.Add("1133311");
            getDataset1().Tables[0].Rows.Add("4444");



        }

        private void searchForColumn_CopyingCellClipboardContent(object sender, DataGridCellClipboardEventArgs e)
        {
            MessageBox.Show("copy");
        }

        private void dtSearchKp2pDataGrid_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e)
        {
            MessageBox.Show("copy2");
        }

        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            Hyperlink _hyperlink = (Hyperlink)sender;
            string navigateUri = _hyperlink.NavigateUri.ToString();
            Process.Start(new ProcessStartInfo(navigateUri));
            e.Handled = true;
        }

        private void button6_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.FileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.Filter = "Text|*.txt" + "|All Files|*.*";
                dlg.ShowDialog();




                string fileName = dlg.FileName.ToString();
                string fileContent = "";


                System.IO.StreamReader objReader = new StreamReader(fileName);

                if (File.Exists(fileName))
                {
                    fileContent = objReader.ReadToEnd();
                }


                List<string> myList = new List<string>(fileContent.Split('\r'));




                foreach (string curStr in myList) // Loop through List with foreach
                {
                    //dtSearchKp2pDataGrid.
                    // Console.WriteLine(curStr.Trim());
                    DataRow dr = getDataset1().Tables[0].NewRow();
                    dr[0] = curStr.Trim();
                    getDataset1().Tables[0].Rows.Add(dr);

                }
            }
            catch (Exception e2) { }


        }

    }
}
